<template>
  <el-form ref="formRef" :model="modelData" label-width="120px" class="mt-20px">
    <el-form-item class="mb-20px">
      <template #label>
        <el-text size="large" tag="b">提交人权限</el-text>
      </template>
      <div class="flex flex-col">
        <el-checkbox v-model="modelData.allowCancelRunningProcess" label="允许撤销审批中的申请" />
        <div class="ml-22px">
          <el-text type="info"> 第一个审批节点通过后，提交人仍可撤销申请 </el-text>
        </div>
      </div>
    </el-form-item>
    <el-form-item v-if="modelData.processIdRule" class="mb-20px">
      <template #label>
        <el-text size="large" tag="b">流程编码</el-text>
      </template>
      <div class="flex flex-col">
        <div>
          <el-input
            v-model="modelData.processIdRule.prefix"
            class="w-130px!"
            placeholder="前缀"
            :disabled="!modelData.processIdRule.enable"
          >
            <template #prepend>
              <el-checkbox v-model="modelData.processIdRule.enable" />
            </template>
          </el-input>
          <el-select
            v-model="modelData.processIdRule.infix"
            class="w-130px! ml-5px"
            placeholder="中缀"
            :disabled="!modelData.processIdRule.enable"
          >
            <el-option
              v-for="item in timeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-input
            v-model="modelData.processIdRule.postfix"
            class="w-80px! ml-5px"
            placeholder="后缀"
            :disabled="!modelData.processIdRule.enable"
          />
          <el-input-number
            v-model="modelData.processIdRule.length"
            class="w-120px! ml-5px"
            :min="5"
            :disabled="!modelData.processIdRule.enable"
          />
        </div>
        <div class="ml-22px" v-if="modelData.processIdRule.enable">
          <el-text type="info"> 编码示例：{{ numberExample }} </el-text>
        </div>
      </div>
    </el-form-item>
    <el-form-item class="mb-20px">
      <template #label>
        <el-text size="large" tag="b">自动去重</el-text>
      </template>
      <div class="flex flex-col">
        <div>
          <el-text> 同一审批人在流程中重复出现时： </el-text>
        </div>
        <el-radio-group v-model="modelData.autoApprovalType">
          <div class="flex flex-col">
            <el-radio :value="0">不自动通过</el-radio>
            <el-radio :value="1">仅审批一次，后续重复的审批节点均自动通过</el-radio>
            <el-radio :value="2">仅针对连续审批的节点自动通过</el-radio>
          </div>
        </el-radio-group>
      </div>
    </el-form-item>

    <el-form-item
      v-if="modelData.summarySetting && modelData.formType === BpmnModelFormTypeEnum.NORMAL"
      class="mb-20px"
    >
      <template #label>
        <el-text size="large" tag="b">摘要设置</el-text>
      </template>
      <div class="flex flex-col">
        <el-radio-group v-model="modelData.summarySetting.enable">
          <div class="flex flex-col">
            <el-radio :value="false">
              系统默认 <el-text type="info"> 展示表单前 3 个字段 </el-text>
            </el-radio>
            <el-radio :value="true"> 自定义摘要 </el-radio>
          </div>
        </el-radio-group>
        <el-select
          class="w-500px!"
          v-if="modelData.summarySetting.enable"
          v-model="modelData.summarySetting.summary"
          multiple
          placeholder="请选择要展示的表单字段"
        >
          <el-option
            v-for="item in formFieldOptions4Summary"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
    </el-form-item>


    <el-form-item class="mb-20px">
      <template #label>
        <el-text size="large" tag="b">全局任务执行监听器</el-text>
      </template>
                <!-- 执行监听器 -->
                <div class="listener-section">
                  <el-table :data="modelData.executionListenerArray" size="small">
                    <el-table-column label="监听器名称" prop="name"></el-table-column>
                    <el-table-column label="事件类型" prop="event"></el-table-column>
                    <el-table-column label="操作" width="100">
                      <template #default="{ $index }">
                        <el-button
                          size="small"
                          type="danger"
                          icon="el-icon-delete"
                          @click="removeListener(taskListenerType, $index)"
                        />
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-button 
                    type="primary" 
                    size="small"
                    @click="openListenerDialog()"
                  >
                    添加执行监听器
                  </el-button>
                  <!-- 监听器选择弹窗 -->
                    <ListenerSelectorDialog
                      :visible="dialogVisible"
                      :listenerType="taskListenerType"
                      @select="handleListenerSelect"
                    />
                </div>
    </el-form-item>
    <el-form-item class="mb-20px">
      <template #label>
        <el-text size="large" tag="b">全局执行监听器</el-text>
      </template>
                <!-- 执行监听器 -->
                <div class="listener-section">
                  <el-table :data="modelData.executionListenerArray" size="small">
                    <el-table-column label="监听器名称" prop="name"></el-table-column>
                    <el-table-column label="事件类型" prop="event"></el-table-column>
                    <el-table-column label="操作" width="100">
                      <template #default="{ $index }">
                        <el-button
                          size="small"
                          type="danger"
                          icon="el-icon-delete"
                          @click="removeListener(executionListenerType, $index)"
                        />
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-button 
                    type="primary" 
                    size="small"
                    @click="openListenerDialog()"
                  >
                    添加执行监听器
                  </el-button>
                  <!-- 监听器选择弹窗 -->
                    <ListenerSelectorDialog
                      :visible="dialogVisible"
                      :listenerType="executionListenerType"
                      @select="handleListenerSelect"
                    />
                </div>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { BpmnUserTaskDuplicateApproveTypeEnum, BpmnModelFormTypeEnum } from '@/utils/constants'
import {API_BPMN_FORM} from '@/api/workflow/bpmnForm'
import {BpmnProcessListenerTypeEnum} from '@/utils/constants'
import ListenerSelectorDialog from './ListenerSelectorDialog.vue'
import {ProcessListenerVO} from '@/api/workflow/bpmnProcessListener.ts'
import { usePlugins } from '@/plugins'
const plugins = usePlugins()

/**
 * 
 * 这段代码表示，如果本组件使用v-model:setting，那么子组件就要用下面的代码来保证动态更新
 * const props = defineProps({
  setting: {
    type: Object,
    required: true
  },
  responseEnable: {
    type: Boolean,
    required: true
  },
  formItemPrefix: {
    type: String,
    required: true
  }
})
const { setting } = toRefs(props)
const emits = defineEmits(['update:setting'])
watch(
  () => setting,
  (val) => {
    emits('update:setting', val)
  }
)
 */

//双向绑定父组件的modelData，自动绑定v-model
const modelData = defineModel<any>()

//默认弹窗关闭
const dialogVisible = ref(false)
const executionListenerType = BpmnProcessListenerTypeEnum.EXECUTION
const taskListenerType = BpmnProcessListenerTypeEnum.TASK

// 打开弹窗
const openListenerDialog = () => {
  dialogVisible.value = true
}


const formFields = ref<string[]>([])
   
const props = defineProps({
  // 流程表单 ID
  modelFormId: {
    type: Number,
    required: false,
    default: undefined,
  }
})


const removeListener = (type:string, index:number) => {
  if (type === 'execution') {
    // ✅ 直接操作数组（不需要创建新数组）
      modelData.value.executionListenerArray.splice(index, 1)
  }else if(type === 'task'){
      modelData.value.taskListenerArray.splice(index, 1)
  }
}



const handleListenerSelect = (type:string,listenerData:ProcessListenerVO[]) => {

    // 1. 确保参数类型正确
  if (!Array.isArray(listenerData) || listenerData.length === 0) {
    plugins.$modal.alertWarning('未接收到有效的监听器数据');
    dialogVisible.value = false;
    return;
  }
  
  // 2. 获取目标数组
  let targetArray: ProcessListenerVO[];
  
  switch (type) {
    case BpmnProcessListenerTypeEnum.EXECUTION:
      if (!modelData.value.executionListenerArray) {
        modelData.value.executionListenerArray = [];
      }
      targetArray = modelData.value.executionListenerArray;
      break;
      
    case BpmnProcessListenerTypeEnum.TASK:
      if (!modelData.value.taskListenerArray) {
        modelData.value.taskListenerArray = [];
      }
      targetArray = modelData.value.taskListenerArray;
      break;
      
    default:
       plugins.$modal.alertError(`未知的监听器类型: ${type}`);
      dialogVisible.value = false;
      return;
  }
  
  // 3. 过滤掉重复项
  const validListeners = listenerData.filter(newListener => {
    // 检查重复逻辑 - 以 id 作为唯一标识
    const isDuplicate = targetArray.some(
      existingListener => existingListener.id === newListener.id
    );
    
    // 如果使用了不同类型，可以检查其他字段组合
    // const isDuplicate = targetArray.some(
    //   existingListener => 
    //     existingListener.name === newListener.name &&
    //     existingListener.event === newListener.event
    // );
    
    if (isDuplicate) {
      console.warn(`跳过重复监听器: ${newListener.name}`);
      return false;
    }
    return true;
  });
  
  // 4. 添加非重复项
  if (validListeners.length > 0) {
    // 扩展运算符确保响应式更新
    targetArray.push(...validListeners);
    
    // 提示添加成功
    plugins.$modal.msgSuccess(`成功添加 ${validListeners.length} 个监听器`);
  } else {
     plugins.$modal.alertWarning('所有选择的监听器都已存在，未添加新记录');
  }
  
  // 5. 关闭对话框
  dialogVisible.value = false;
}




// 监听 modelFormId 变化
watch(
  () => props.modelFormId,
  async (newVal) => {
    if (newVal) {
      const form = (await API_BPMN_FORM.getForm(newVal)).data;
      formFields.value = form?.fields;
    } else {
      // 如果 modelFormId 为空，清空表单字段
      formFields.value = [];
    }
  },
  { immediate: true },
);
// 暴露给子组件使用
provide('formFields', formFields)

/** 自定义 ID 流程编码 */
const timeOptions = ref([
  {
    value: '',
    label: '无'
  },
  {
    value: 'DAY',
    label: '精确到日'
  },
  {
    value: 'HOUR',
    label: '精确到时'
  },
  {
    value: 'MINUTE',
    label: '精确到分'
  },
  {
    value: 'SECOND',
    label: '精确到秒'
  }
])
const numberExample = computed(() => {
  if (modelData.value.processIdRule.enable) {
    let infix = ''
    switch (modelData.value.processIdRule.infix) {
      case 'DAY':
        infix = dayjs().format('YYYYMMDD')
        break
      case 'HOUR':
        infix = dayjs().format('YYYYMMDDHH')
        break
      case 'MINUTE':
        infix = dayjs().format('YYYYMMDDHHmm')
        break
      case 'SECOND':
        infix = dayjs().format('YYYYMMDDHHmmss')
        break
      default:
        break
    }
    return (
      modelData.value.processIdRule.prefix +
      infix +
      modelData.value.processIdRule.postfix +
      '1'.padStart(modelData.value.processIdRule.length - 1, '0')
    )
  } else {
    return ''
  }
})

/** 是否开启流程前置通知 */
const processBeforeTriggerEnable = ref(false)
const handleProcessBeforeTriggerEnableChange = (val: boolean | string | number) => {
  if (val) {
    modelData.value.processBeforeTriggerSetting = {
      url: '',
      header: [],
      body: [],
      response: []
    }
  } else {
    modelData.value.processBeforeTriggerSetting = null
  }
}

/** 是否开启流程后置通知 */
const processAfterTriggerEnable = ref(false)
const handleProcessAfterTriggerEnableChange = (val: boolean | string | number) => {
  if (val) {
    modelData.value.processAfterTriggerSetting = {
      url: '',
      header: [],
      body: [],
      response: []
    }
  } else {
    modelData.value.processAfterTriggerSetting = null
  }
}

/** 是否开启任务前置通知 */
const taskBeforeTriggerEnable = ref(false)
const handleTaskBeforeTriggerEnableChange = (val: boolean | string | number) => {
  if (val) {
    modelData.value.taskBeforeTriggerSetting = {
      url: '',
      header: [],
      body: [],
      response: []
    }
  } else {
    modelData.value.taskBeforeTriggerSetting = null
  }
}

/** 是否开启任务后置通知 */
const taskAfterTriggerEnable = ref(false)
const handleTaskAfterTriggerEnableChange = (val: boolean | string | number) => {
  if (val) {
    modelData.value.taskAfterTriggerSetting = {
      url: '',
      header: [],
      body: [],
      response: []
    }
  } else {
    modelData.value.taskAfterTriggerSetting = null
  }
}

/** 表单选项 */
const formField = ref<Array<{ field: string; title: string }>>([])

const formFieldOptions4Summary = computed(() => {
  return formField.value.map((item) => {
    return {
      label: item.title,
      value: item.field
    }
  })
})

/** 兼容以前未配置更多设置的流程 */
const initData = () => {
  if (!modelData.value.processIdRule) {
    modelData.value.processIdRule = {
      enable: false,
      prefix: '',
      infix: '',
      postfix: '',
      length: 5
    }
  }
  if (!modelData.value.autoApprovalType) {
    modelData.value.autoApprovalType = BpmnUserTaskDuplicateApproveTypeEnum.NONE
  }
  if (!modelData.value.titleSetting) {
    modelData.value.titleSetting = {
      enable: false,
      title: ''
    }
  }
  if (!modelData.value.summarySetting) {
    modelData.value.summarySetting = {
      enable: false,
      summary: []
    }
  }
  if (modelData.value.processBeforeTriggerSetting) {
    processBeforeTriggerEnable.value = true
  }
  if (modelData.value.processAfterTriggerSetting) {
    processAfterTriggerEnable.value = true
  }
  if (modelData.value.taskBeforeTriggerSetting) {
    taskBeforeTriggerEnable.value = true
  }
  if (modelData.value.taskAfterTriggerSetting) {
    taskAfterTriggerEnable.value = true
  }
}
defineExpose({ initData })


</script>
